package com.lxk.concurrency.example.syncContainer;

import java.util.Iterator;
import java.util.Vector;

import com.lxk.concurrency.annoations.NotThreadSafe;

@NotThreadSafe
public class VectorExample3 {

	// java.util.ConcurrentModificationException
	private static void test1(Vector<Integer> v1) { // foreach
		for (Integer i : v1) {
			if (i.equals(3))
				v1.remove(i);
		}
	}

	// java.util.ConcurrentModificationException，使用迭代器提供的 remove 方法就没事
	private static void test2(Vector<Integer> v2) { // iterator
		Iterator<Integer> iterator = v2.iterator();
		while (iterator.hasNext()) {
			Integer i = iterator.next();
			if (i.equals(3))
				v2.remove(i);
		}

	}

	// success
	private static void test3(Vector<Integer> v3) { // for

		for (int i = 0; i < v3.size(); i++) {
			if (v3.get(i).equals(3))
				v3.remove(i);
		}
	}

	public static void main(String[] args) {

		Vector<Integer> vector = new Vector<Integer>();
		vector.add(1);
		vector.add(2);
		vector.add(3);

		test3(vector);
	}
}